package com.razorfish.configuration.condition 
{
	import com.razorfish.configuration.entities.ConfigObject;
	import com.razorfish.configuration.entities.ConfigObjectType;
	import com.razorfish.configuration.entities.KeyTypePair;
	import com.razorfish.configuration.entities.PredefinedProperty;
	import com.razorfish.configuration.entities.SingleConfigObject;
	import com.razorfish.configuration.parsers.UnknownValue;
	/**
	 * ...
	 * @author derek
	 */
	public class Condition extends ConfigObject
	{
		private var _isCaculated:Boolean;
		private var _result:Boolean;
		
		public function Condition(data:String)
		{
			super(data);
		}
		
		private function caculate():void
		{
			var regex:RegExp = /^'([^']+?)'\s*([^\s']+)\s*'([^']+?)'$/;
			var result:Object = regex.exec(originalData);
			if (result == null || result.length != 4)
			{
				throw new Error("Invalid condition format");
			}
			else
			{
				var operator:String = result[2];
				if (!Operator.isValid(operator))
				{
					throw new Error("Invalid operator");
				}
				else
				{
					var leftOperand:UnknownValue = new UnknownValue(result[1]);
					var rightOperand:UnknownValue = new UnknownValue(result[3]);
					
					leftOperand.tryGetValue();
					rightOperand.tryGetValue();
					
					if (leftOperand.isKnown && rightOperand.isKnown)
					{
						_result = Operator.caculate(leftOperand.value, operator, rightOperand.value);
						_isCaculated = true;
					}
					else
					{
						if(!leftOperand.isKnown)
							throw new Error("Invalid left condition operand");
						else if (!rightOperand.isKnown)
							throw new Error("Invalid right condition operand");
					}
				}
			}
		}
		
		public function get result():Boolean
		{
			if (!_isCaculated) caculate();
			return _result;
		}
	}
}
